//获取应用实例
var webim = require('../../utils/webim_wx.js');
var webimhandler = require('../../utils/webim_handler.js');
var tls = require('../../utils/tls.js');

// var fileData = require('../../utils/userSig.js');

var msgHandle=require('../../utils/msgHandle.js');
//获取应用实例
var app=getApp();

global.webim = webim;


Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    msgs: [],
    Identifier: app.globalData.identifier,
    UserSig: app.globalData.userSig,
    msgContent: "",
    newslist: [],
    currentMsgsArray:[],
    selSess: {},
    selType: webim.SESSION_TYPE.C2C,
    scrollTop: 0,
    sentTo:"",
    data:""
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  clearInput: function() {
    // this.setData({
    //   msgContent: ""
    // })
  },
  //获取普通文本消息
  bindKeyInput: function(e) {
    var that = this;
    that.setData({
      msgContent: e.detail.value
    })
  },

//end function login


  submit: function (e) {
    console.log("the formId is %o",e.detail.formId);
  },
  //end submit
  //点击发送按钮，发送消息
  send: function(e) {
    var that = this;
    if (that.data.msgContent.length<1){
      wx.showToast({
        title: '发送不得为空',
        duration: 1000,
        mask: true,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      });
      return false;
    }
    
    //获取消息内容
    var msgtosend = that.data.msgContent;
   
    var msgLen = webim.Tool.getStrBytes(msg);
    var selType = webim.SESSION_TYPE.C2C;
    //
    var sendtoid = that.data.sentTo;
    // 创建会话对象

    var selSess = new webim.Session(selType, sendtoid);

    var isSend = true; //是否为自己发送
    var seq = -1; //消息序列，-1表示sdk自动生成，用于去重
    var random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
    var msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
    var subType = webim.C2C_MSG_SUB_TYPE.COMMON; //消息子类型c2c消息时，参考c2c消息子类型对象：webim.C2C_MSG_SUB_TYPE 
    //loginInfo.identifier消息发送者账号,loginInfo.identifierNick消息发送者昵称
    var msg = new webim.Msg(selSess, isSend, seq, random, msgTime, app.globalData.identifier, subType);
    //解析文本和表情
    var expr = /\[[^[\]]{1,3}\]/mg;
    var emotions = msgtosend.match(expr);
    var text_obj = new webim.Msg.Elem.Text(msgtosend);
    console.log("the msgtosend is " + msgtosend)
    msg.addText(text_obj);
    // if (!emotions || emotions.length < 1) {
    //   var text_obj = new webim.Msg.Elem.Text(msgtosend);
    //   msg.addText(text_obj);
    // } else { //有表情

    // }
    console.log("the msg to send is ");
    console.log(msg);
    webim.sendMsg(msg, function(resp) {

      webim.Log.info("发消息成功");
      msgHandle.addMsg(msg,that.data.currentMsgsArray,function(res){
        that.setData({
          currentMsgsArray:res
        });
        //page scroll to bottom after webim send the message.
        that.pageScrollToBottom();
        
        that.NotifyReceiver();
        
        
      });
    }, function(err) {
      webim.Log.error("发消息失败:" + err.ErrorInfo);
    });

  },
//end send message function

  receiveMsgs: function(data) {
    var msgs = this.data.msgs || [];
    msgs.push(data);
    //最多展示10条信息
    if (msgs.length > 10) {
      msgs.splice(0, msgs.length - 10)
    }

    this.setData({
      msgs: msgs
    })
  },

  initIM: function (username, userSig,sentTo) {
    var that = this;
    //用户信息对象
    msgHandle.msgHandleInit(username, userSig);
    var loginInfo = msgHandle.loginInfo;
    var options = msgHandle.options;
    var listeners = {
      "onConnNotify": webimhandler.onConnNotify,
      "onMsgNotify": function (msg) {
        webimhandler.onMsgNotify(msg, function () {
          console.log("callback in consultchat");
          console.log("right here in consultchat %o", msg[0]);
          msgHandle.addMsg(msg[0], that.data.currentMsgsArray, function (res) {
            that.setData({
              currentMsgsArray: res
            });

            that.pageScrollToBottom();
            
          });
        })
      }
    };

    if (webim.checkLogin()) { //检查是否登录返回true和false,不登录则重新登录
      console.log('consultchat,已登录，the loginInfo is' + loginInfo);
      console.log(loginInfo);
      //must login first
      webim.login(loginInfo, listeners, options, function () {
        console.log("initIM,登录成功");
        that.getLastC2CHistoryMsgs();
      });
    } else {
      //must login first
      webim.login(loginInfo, listeners, options,function () {
        console.log("initIM,登录成功");
        that.getLastC2CHistoryMsgs();
      });
    }
    
  },
  //end function initIM
  
  getLastC2CHistoryMsgs: function() {
    var that = this;
    console.log("now,let's get the history message.")
    // if (selType == webim.SESSION_TYPE.GROUP) {
    //   console.log('当前的聊天类型为群聊天，不能进行拉取好友历史消息操作');
    //   return;
    // }
    var lastMsgTime = 0; //第一次拉取好友历史消息时，必须传 0
    var msgKey = '';
    var selToID = that.data.sentTo;
    var options = {
      'Peer_Account': that.data.sentTo, //好友帐号
      'MaxCnt': 10, //拉取消息条数
      'LastMsgTime': 0, //最近的消息时间，即从这个时间点向前拉取历史消息
      'MsgKey': ''
    };
    var selSess = null;
    webim.getC2CHistoryMsgs(
      options,
      function(resp) {
        var complete = resp.Complete; //是否还有历史消息可以拉取，1-表示没有，0-表示有
        var retMsgCount = resp.MsgCount; //返回的消息条数，小于或等于请求的消息条数，小于的时候，说明没有历史消息可拉取了
        if (resp.MsgList.length == 0) {
          webim.Log.error("没有历史消息了:data=" + JSON.stringify(options));
          return;
        }
        //拉取消息后，要将下一次拉取信息所需要的东西给存在缓存中
        wx.setStorageSync('lastMsgTime', resp.LastMsgTime);
        wx.setStorageSync('msgKey', resp.MsgKey);
        var msgList = resp.MsgList;
        for (var j in msgList) { //遍历新消息
          var msg = msgList[j];
          if (msg.getSession().id() == selToID) { //为当前聊天对象的消息
            selSess = msg.getSession();
            //在聊天窗体中新增一条消息
            msgHandle.addMsg(msg, that.data.currentMsgsArray, function (res) {
              that.setData({
                currentMsgsArray: res
              });
            });
          }
        }
        //消息已读上报，并将当前会话的消息设置成自动已读
        webim.setAutoRead(selSess, true, true);

        that.pageScrollToBottom();
      },
      function(responsedata) {
        console.log("can not get the history message." + responsedata.ErrorInfo);
      }
    );
  },
  // end function getLastC2CHistoryMsgs
  onLoad: function(event) {
    var that = this;
    var telephone = app.globalData.identifier;
    console.log("the app.globalData.identifier; is ", telephone);
    var userSig = app.globalData.userSig;
    console.log("the app.globalData.userSig; is ", userSig);

    // 获取URL参数
    console.log("the URL parameter field is " + event.field);

    if (event.sentTo) {
      console.log("the URL parameter sentTo is " + event.sentTo);
      that.setData({
        sentTo: event.sentTo
      });
    }
    //登录
    console.log("the local sentTo is " + that.data.sentTo)
    that.initIM(telephone, userSig, that.data.sentTo);
   


  },
  // end onload

  // 滚动最底部
  pageScrollToBottom: function () {
    wx.createSelectorQuery().select('#chat').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.height
      })
    }).exec()
  },
  // end pageScrollToBottom

  onShow:function(){
    this.pageScrollToBottom();
    
  },
  //end 

  formSubmit: function (e) {
    console.log("the all form id is ",e.detail.formId);
      console.log("the telephone is %o", app.globalData.identifier);
    wx.request({
      url: "https://www.xuezhou.xyz/storeFormID",
      data: {
        "telephone": app.globalData.identifier,
        "formID": e.detail.formId,
        "openID": app.globalData.openid
      },
      success: function (res) {
        console.log("the return of consultantRegister is:" + res.data);
        console.log(res);
        wx.setStorage({
          key: "isRegistered",
          data: true
        });

      },
      fail: function (resp) {
        console.log("registered failed，the response is %o", resp);
        return false;
      },
      complete: function (res) {
        // console.log("the return of consultantRegister complete is:" + res.data);
        // console.log(res);
      } //请求完成后执行的函数
    })
  // 结束wx.request
  },
  NotifyReceiver(){
    var that = this;
    wx.request({
      url: "https://www.xuezhou.xyz/NotifyReceiver",
      data: {
        "receiver": that.data.sentTo,
        "sender": app.globalData.identifier,
        "access_token":app.globalData.access_token,
        "msgContent": that.data.msgContent,
        "companyName": app.globalData.companyName
        // "telephone": "17722656615"
      },
      success: function (res) {
        console.log("the return of getFormIDByTelephone is:%o", res.data)
      },
      fail: function (resp) {
        console.log("registered failed，the response is %o", resp);
        return false;
      },
      complete: function (res) {
        that.setData({
          msgContent: ""
        })
      }
       
    })
  // 结束wx.request
  },
  //end NotifyReceiver

  getFormIDByTelephoneAndNotify:function(){
    var that=this;
    wx.request({
      url: "https://www.xuezhou.xyz/getFormIDByTelephone",
      data: {
        "telephone": that.data.sentTo
        // "telephone": "17722656615"
      },
      success: function (res) {
        console.log("the return of getFormIDByTelephone is:%o", res.data[0]);
        console.log("the form ID  is ", res.data[0].formID);
        console.log("the open ID  is ", res.data[0].openID);
        that.notifyReceiver(res.data[0].formID, res.data[0].openID)
      },
      fail: function (resp) {
        console.log("registered failed，the response is %o", resp);
        return false;
      },
      complete: function (res) {
        // console.log("the return of consultantRegister complete is:" + res.data);
        // console.log(res);
      } //请求完成后执行的函数
    })
  // 结束wx.request
  }


})
//end Page

